/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.gob.fonafe.action;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.opensymphony.xwork2.ActionSupport;
import java.lang.reflect.Type;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import pe.gob.fonafe.domain.UbigeoBean;
import pe.gob.fonafe.service.UsuarioService;

/**
 *
 * @author czela
 */
public class CargarUbigeoAction extends ActionSupport implements ServletResponseAware{

   private HttpServletResponse response;

    @Autowired
   private UsuarioService usuarioService;
    
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String execute() throws Exception {
        List<UbigeoBean> listUbigeoTemp = usuarioService.getListUbigeos();

        GsonBuilder gsonb = new GsonBuilder();
        gsonb.registerTypeAdapter(UbigeoBean.class, new PalabrasSerializer());
        Gson gson = gsonb.create();
        ServletOutputStream sos = response.getOutputStream();
        sos.print(gson.toJson(listUbigeoTemp));
        return null;//devuelve en json
        
    }

    private static class PalabrasSerializer implements JsonSerializer<UbigeoBean>{

        public JsonElement serialize(UbigeoBean src, Type type, JsonSerializationContext jsc) {
            JsonObject jObject = new JsonObject();
            jObject.add("id", new JsonPrimitive(src.getId()));
            jObject.add("label", new JsonPrimitive(src.getDepartamento() + "-" + src.getProvincia() + "-" + src.getDistrito()));
            jObject.add("value", new JsonPrimitive(src.getDepartamento() + "-" + src.getProvincia() + "-" + src.getDistrito()));
            return jObject;
        }

    }




}
